from django.utils.deprecation import MiddlewareMixin

from menus.models import OperationLog
from utils.JwtTool import Jwt


# 自定义中间件  实现强制登陆
class CheckUserMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 获取请求头中的token
        token = request.headers.get('token')
        # print(token)
        # 判断token是否存在
        if not token:
            # 给request添加user_info字段保存用户信息
            request.user_info = None
        else:
            payload = Jwt().valid_jwt(token)
            request.user_info = payload
            # print(payload)


            method = request.method
            if method == 'GET':
                info = f'查看了{request.path}中的数据'
            if method == 'POST':
                info = f'更新了{request.path}中的数据'
            if method == 'PUT':
                info = f'修改了{request.path}中的数据'
            if method == 'DELETE':
                info = f'删除了{request.path}中的数据'
            OperationLog.objects.create(staff_id=payload['id'], content=info)
